<template>
  <div>
    <el-breadcrumb class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'NewsList'}">新闻中心</el-breadcrumb-item>
      <el-breadcrumb-item >新增新闻</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form  label-width="100px" class="demo-ruleForm"
              :model="news"  ref="news" style="margin-top: 30px"
    >
      <table class="btm" v-loading="loading">
        <el-form-item label="新闻标题" prop="resource">
          <el-input v-model="news.newsTitle" placeholder="请输入新闻标题" style="width: 350px"></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="resource">
          <el-input v-model="news.createPerson" style="width: 160px" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item style="width: 800px">
          <div id="wangEditor"></div>
        </el-form-item>
      </table>
      <el-form-item>
        <el-button type="primary" @click="insertNews">立即创建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import wangEditor from 'wangeditor'
  export default {
    name: "add-news",
    data(){
      return {
        loading:'',
        editor: null,
        news:{
          newsTitle:'',
          createPerson:'',
          newsContent:''
        }
      }
    },
    created(){
      this.news.createPerson=this.$store.state.admin.name;
    },
    mounted() {
      const editor = new wangEditor(`#wangEditor`);
      editor.config.height = 400;

      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = (newHtml) => {
        this.news.newsContent = newHtml
      };
      // 创建编辑器
      editor.create();
      this.editor = editor
    },
    methods:{
      insertNews(){
        this.$ajax.post(this.$config.url + `news/addNews`,this.news
        ).then(res => {
          if(res.data.message=="succ"){
            this.$message.success("增加成功");
            this.$router.push("NewsList");
          }else{
            this.$message.error("出错了，添加失败")
          }
        }).finally(() => {
        })
      },
    },
    beforeDestroy() {
      // 调用销毁 API 对当前编辑器实例进行销毁
      this.editor.destroy()
      this.editor = null
    }
  }
</script>

<style scoped>

</style>